﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Dropthings.Test.Rules;

namespace Inventory.Test.Library.Rules
{
    [DisplayName("Extract Grid Action Buttons")]
    [Description("Extract all action buttons exists in a row which contains certain link")]
    public class ExtractGridActionButtons : ExtractionRule
    {
        public const string GRID_PREFIX = "$GRID.";


        private string _UrlTargtedInEditLink = string.Empty;


        [Description("Url to detect its container row, then getting all action buttons in the same row, for example 'Company_edit.aspx={{CompanyID}}' where 'CompanyID' is web test context parameter")]
        public string UrlTargtedInEditLink
        {
            get
            {
                if (_UrlTargtedInEditLink == null)
                    _UrlTargtedInEditLink = "";

                return _UrlTargtedInEditLink;
            }
            set
            {
                if (value != string.Empty)
                    _UrlTargtedInEditLink = value;
            }
        }

        string findPaggerButtonsPattern = @"Page\$[^']";


        public override void Extract(object sender, ExtractionEventArgs e)
        {

            string pattern = string.Format(@"<a\s\s*id=(?<id>[^\s]*).*href=(?<href>.*{0})[^>]", this.UrlTargtedInEditLink.Replace("?", "\\?"));
            int startFromIndex = UrlTargtedInEditLink.IndexOf('=') + 1;
            string entityID = this.UrlTargtedInEditLink.Substring(startFromIndex, UrlTargtedInEditLink.Length - startFromIndex);

            Regex _FindAnchorTags = new Regex(
            pattern,
            RegexOptions.IgnoreCase
            | RegexOptions.Multiline
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );

            Regex _FindPaggerButtonsPattern = new Regex(
            findPaggerButtonsPattern,
            RegexOptions.IgnoreCase
            | RegexOptions.Multiline
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );


            string body = e.Response.BodyString;
            var extractMatches = _FindAnchorTags.Matches(body);

            List<string> formElements = new List<string>();


            for (int i = 0; i < extractMatches.Count; i++)
            {
                Match extractMatch = extractMatches[i];
                string editButtonID = extractMatch.Groups["id"].Value.Replace("_", "$").Replace("\"", "");
                string buttonIDPrefix = editButtonID.Substring(0, editButtonID.LastIndexOf("$"));
                string deleteButtonID = buttonIDPrefix + "$DeleteLinkButton";

                int gridNumber = i;
                string shortKey = GRID_PREFIX + gridNumber + ".DeleteLinkButton.EntityID";
                e.WebTest.Context[shortKey] = deleteButtonID;

                e.Success = true;
            }

            var paggerMatches = _FindPaggerButtonsPattern.Matches(body);
            if (paggerMatches.Count > 0 && !e.WebTest.Context.ContainsKey("GoToLastGridPage"))
            {
                e.WebTest.Context["GoToLastGridPage"] = paggerMatches[paggerMatches.Count - 1].Value;
            }

            if (e.Success)
                e.Message = "Query string parameter extracted.";
            else
                e.Message = "No query string parameter extracted.";
        }
    }
}
